import router from './router/index'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

// 白名单
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 当前token为空
  if (store.getters.tokenValue === '') {
    // 是否是白名单
    if (whiteList.indexOf(to.path) === -1) {
      next('/login')
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('PullUserInfo').then(data => {
          let menus = data.menus
          let username = data.username
          store.dispatch('GenerateRouter', {menus, username}).then(() => {
            router.addRoutes(store.getters.addRouters)
            next({...to, replace: true})
          })
        })
      }
    }
    next()
  }
})
router.afterEach(() => {
  NProgress.done()
})
